#!/usr/bin/env python
# coding:utf-8

from __future__ import print_function
import sys
import os
import getopt
import shutil
import random
import string
from filesearch import ExtensionTester
from filesearch import FileTester
from filesearch import test_filename
from consts import TEMP_PATH


def search_file(keywords, directory, extension, case_sensitive, search_all):
    extTester = ExtensionTester(extension)
    fileTeste = FileTester(keywords, case_sensitive)
    print('Searching for {} in files with these extensions:'.format(keywords), extTester.extensions)
    print('Root directory: {}'.format((directory or os.getcwd())), '\n')
    filenames = []
    for (dirpath, subdirs, files) in os.walk((directory or os.getcwd())):
        for x in files:
            try:
                if extTester.test(x) and (fileTeste.test(os.path.join(dirpath, x)) or test_filename(keywords, x)):
                    filenames.append(os.path.join(dirpath, x))
                    print(os.path.join(dirpath, x))
                    if not search_all:
                        return True
            except UnicodeDecodeError:
                pass
    print('\n{} results.'.format(len(filenames)))
    if len(filenames) > 0:
        return True
    else:
        return False

def random_string(length):
    seed = "1234567890abcdefghijklmnopqrstuvwxyz"
    sa = []
    for i in range(length):
        sa.append(random.choice(seed))
    salt = ''.join(sa)
    return salt

def apk_search(apk, keywords, case_sensitive, search_all, use_fetcher):
    try:
        if not os.path.exists(TEMP_PATH):
            os.mkdir(TEMP_PATH)
        apk_hash = ""
        if use_fetcher:
            apk_path = TEMP_PATH + apk + ".apk"
            apk_hash = apk
        else:
            apk_path = apk
            apk_hash = random_string(10)
        apk_decoded_path = TEMP_PATH + apk_hash
        if use_fetcher:
            os.system("python ./apk_fetcher.py " + apk_hash)
        os.system("java -jar ./apktool.jar -r d " + apk_path + " -o " + apk_decoded_path)
        result = search_file(keywords, apk_decoded_path + "/smali", ["smali"], case_sensitive, search_all)
        print (result)
    except Exception, e:
        print("Error " + e.message)
    if use_fetcher:
        os.remove(apk_path)
    shutil.rmtree(apk_decoded_path)
    return result


if __name__ == '__main__':
    try:
        options, args = getopt.getopt(sys.argv[1:], "sah:d:")
    except getopt.GetoptError:
        print ("Usage: apk_search.py (-s)(-a)-d[apk_path] or -h[apk_hash] [keyword1] [keyword2]...")
        print ("-s for case sensitive, -a to search all files in apk(will stop on first keyword found by default)")
        sys.exit()

    case_sensitive = False
    search_all = False
    use_fetcher = False
    apk = ""
    for option, value in options:
        if option == "-s":
            case_sensitive = True
        elif option == "-h":
            apk = value
            use_fetcher = True
        elif option == "-d":
            apk = value
            use_fetcher = False
        elif option == "-a":
            search_all = True

    keywords = args
    apk_search(apk, keywords, case_sensitive, search_all, use_fetcher)


